<?php
//	product.inc.php
// 	This file contains most of the functions related to product management (insertion, modification, display..)
// 	See also, for the functions that uses the class:Product, product.class.php

// THE FOLLOWING FUNCTIONS ARE FROM SHOW_PRODUCT.INC.PHP
	
function check_product($db, $pr)
{
	if(is_numeric($pr))
	{
		$req = $db->query('SELECT pr_id FROM jktrade_products WHERE pr_id = '.$pr.'');
		$data = $req->fetch();

		if($data) // Required product exists  
		{ 	 
			$pr = $data['pr_id'];
		}
	}
	
	else if($pr != "All")	// Required product doesn't exist, we send back a null value
	{
		$pr = 0;
	}

	return $pr;
}

function getCatName($db, $id)
{
	$req = $db->query('SELECT cat_name FROM jktrade_cat WHERE cat_id = '.$id.'');
	$data = $req->fetch();
	
	return $data['cat_name'];
}


function show_product($db)
{	
	 if(!isset($catName)){$catName = "unavailable";}
	 
	 return array ($catName);
}		

function getRandomProducts($db, $cat) // Get 10 products ID randomly picked
{
	$randomProducts = array();
	$subcats = search_sub_cat($db, $cat);
	$nbProducts = count_product($db, $cat, $subcats);
	
	if(!$cat) //If no specific category is required -> "All"
	{
		$query_string = "SELECT pr_id FROM jktrade_products";
	}
	else if (!$subcats) //Selected cat is already a sub-category or doesn't own any sub-cat
	{
		$query_string = "SELECT pr_id FROM jktrade_products WHERE pr_cat = $cat";
	}
	else //If there are sub-cats
	{
		$query_string = 'SELECT pr_id FROM jktrade_products WHERE pr_cat = '.$subcats[0].' ';
				
		for($i=1; $i<(count($subcats)); $i++)
		{
			$query_string .= 'OR pr_cat ='.$subcats[$i].' ';
		}
	}

	//We create the final query
	$reqpr = $db->query($query_string);
	$allProducts = $reqpr->fetchAll(PDO::FETCH_COLUMN, 0);
	
	if($nbProducts<8)
	{
		$nbRandom = $nbProducts;
	}
	else $nbRandom = 8;
	
	for($i=0; $i<$nbRandom; $i++) // We know randomly select 10 products among all the products of the cat
	{
		do{
			$selected = $allProducts[rand(0, ($nbProducts-1))];
		}while(in_array($selected, $randomProducts));
		
		$randomProducts[$i] = $selected;
	}
	
	return $randomProducts;
}

function displayRandomProducts($db, $cat)
{
	$randomProductsID = getRandomProducts($db, $cat); // n-ID of randomly picked products
	$randomProducts = array();
	$nbRandom = count($randomProductsID);
		
	for($i=0; $i<$nbRandom; $i++) // We instantiate and display the n objects [Product]
	{
		$randomProducts[$i] = new Product($db, $randomProductsID[$i]);
		
		echo'
			<div class="slider-item">
				<div class="slider-image"> 
				<div class="hover_colour">
				<a href="img/uploads/products/large/'.$randomProducts[$i]->mainpic.'" data-rel="prettyPhoto[portfolio1]">
				<img src="img/uploads/products/thumb/'.$randomProducts[$i]->mainpic.'"/></a>
				</div>
				<a class="related_link" href="show_product.php?pr='.$randomProducts[$i]->id.'">'.$randomProducts[$i]->name.'</a>
				</div>
			</div>';
	}
}

function getLatestProducts($db) // Get the ID of the latest array for the function below
{
	$req1 = $db->query("SELECT COUNT(pr_id) as nbProducts FROM jktrade_products");
	$data1 = $req1->fetch();
	
	$last = $data1['nbProducts'];
	if($last>10)
	{
		$last = 10;
	}
						
	$req2 = $db->query("SELECT pr_id FROM jktrade_products 
						ORDER BY pr_date DESC
						LIMIT 0,$last");

	return $req2->fetchAll(PDO::FETCH_COLUMN, 0);
}

function displayLatestProducts($db) // The title says it all [For index.php]
{
	$latestProductsID = getLatestProducts($db); 
	
	$latestProducts = array();
	$nbLatest = count($latestProductsID);
		
	for($i=0; $i<$nbLatest; $i++) // We instantiate and display the n objects [Product]
	{
		$latestProducts[] = new Product($db, $latestProductsID[$i]);
		
		echo'
			<div style="width: 229px;" class="slider-item">
				<div class="slider-image"> 
				<div class="hover_colour">
				<a href="img/uploads/products/large/'.$latestProducts[$i]->mainpic.'" rel="prettyPhoto[portfolio1]">
				<img src="img/uploads/products/thumb/'.$latestProducts[$i]->mainpic.'"/></a>
				</div>
				<a class="related_link" href="show_product.php?pr='.$latestProducts[$i]->id.'">'.$latestProducts[$i]->name.'</a>
				</div>
			</div>';
	}
}

// Indicates if the product can be displayed for everyone or has been withdrawn by the seller or the administrator
function checkDisplay($db, $id)
{
	$req = $db->query('SELECT pr_display FROM jktrade_products WHERE pr_id = '.$id.'');
	$display = $req->fetch();
	
	return $display['pr_display'];
}

// This function is called for each action that may modify the cart
function actionCart($action, $pr_id)
{
	if($action == "addToCart") // If the user adds a product to his cart
	{
		$alreadyInCart = false;
				
		if(empty($_SESSION['cart']))
		{
			$_SESSION['cart'] = array(	"pr_id"  => array ($pr_id),
										"nb_item" => array (1),				
			);
		}
		else
		{
			$length = count($_SESSION['cart']['pr_id']);
			
			for($i = 0; $i < $length; $i++)
			{
				if($_SESSION['cart']['pr_id'][$i] == $pr_id)
				{
					$_SESSION['cart']['nb_item'][$i]++; 
					$alreadyInCart = true;
				}	
			}
			if (!$alreadyInCart)
			{
				array_push($_SESSION['cart']['pr_id'], $pr_id);
				array_push($_SESSION['cart']['nb_item'], 1);
			}
		}
	}
	
	else if($action == "removeFromCart") // If the user removes a product to his cart
	{
		$found = false;
		$length = count($_SESSION['cart']['pr_id']);
		
		if($pr_id == "All")
		{
			unset($_SESSION['cart']['pr_id']);
			unset($_SESSION['cart']['nb_item']);
		}
		else
		{
			for($i = 0; $i < $length; $i++)
			{
				if($_SESSION['cart']['pr_id'][$i] == $pr_id)
				{
					$_SESSION['cart']['pr_id'][$i] = $_SESSION['cart']['pr_id'][$length-1]; 
					$_SESSION['cart']['nb_item'][$i] = $_SESSION['cart']['nb_item'][$length-1];
					
					$found = true;
				}
			}
			if($found)
			{
				array_pop($_SESSION['cart']['pr_id']);
				array_pop($_SESSION['cart']['nb_item']);
			}
		}
		
	}
}

function remplirCart()
{
	if(empty($_SESSION['cart']['pr_id']))
	{
		for($i=0; $i<17; $i++)
		{
			$_SESSION['cart']['pr_id'][$i] = $i+1; 
			$_SESSION['cart']['nb_item'][$i] = 1;
		}
	}
}

function getInfosCart($Products, $type) // This function returns 2 informations about the whole Cart: Price & Quantity 
{
	$nbItems = 0;
	$totalCost = 0;
	$result = 0;
	$length = count($_SESSION['cart']['pr_id']);
	
	if(!empty($_SESSION['cart']['pr_id']))
	{
		switch($type)
		{
			case "itemsQuantity":
			{
				foreach($_SESSION['cart']['nb_item'] as $value)
				{
					$nbItems += $value;
				}
				$result = $nbItems;
			}
			break;
			
			case "itemsPrice":
			{
				for($i=0; $i<$length; $i++)
				{
					$totalCost += $Products[$i]->price*$_SESSION['cart']['nb_item'][$i];
				}
				$result = $totalCost;
			}
			break;
		}
	}
	
	return $result;
}

function createNewOrder($db, $Products, $userID)
{
	$str_prID = serialize($_SESSION['cart']['pr_id']);
	$str_prQuantity = serialize($_SESSION['cart']['nb_item']);
	$cartValue = getInfosCart($Products, "itemsPrice");
	$actualDate = date("Y-m-d H:i:s");

	$req = $db->prepare('INSERT INTO jktrade_orders(ord_user, ord_products, ord_quantity, ord_price, ord_date) 
													VALUES(:ord_user, :ord_products, :ord_quantity, :ord_price, :ord_date)');
	$req->execute(array(
		'ord_user' => $userID,
		'ord_products' => $str_prID,
		'ord_quantity' => $str_prQuantity,
		'ord_price' => $cartValue,
		'ord_date' => $actualDate
	));
}

function isUsersOrder($db, $user, $id)
{
	$req = $db->query('SELECT ord_id FROM jktrade_orders 
						WHERE ord_user ='.$user->id.' AND ord_id ='.$id.'');
	$data = $req -> fetch();
	
	if(!$data){ // If the user doesn't own the product
		$own = 0;
	}
	else $own = 1;
	
	return $own;
}

function isAvailable($db, $id) // Checks if a product is available for sale
{
	$available = false;
	
	$req = $db->query('SELECT pr_display FROM jktrade_products 
						WHERE pr_id ='.$id.'');
	if($data = $req -> fetch())
	{
		if($data['pr_display'])
		{
			$available = true;
		}
	}
	
	return $available;
}

// THE FOLLOWING FUNCTIONS ARE FROM SELL_YOURS.INC.PHP 

function getNbProducts($db, $id) // Return how many products the user already sells
{
	$req = $db->query('SELECT COUNT(pr_id) as nbProducts FROM jktrade_products
						WHERE pr_sellerID = '.$id.'');
	$data = $req->fetch();
	return $data['nbProducts'];
}	

function displaySelectCategories($db)
{
	$req = $db->query('SELECT cat_id, cat_name FROM jktrade_cat WHERE cat_id>1');
	$data = $req->fetchAll();
	
	echo '<select name="pr_cat" placeholder="Product Category">
		  <option value="" disabled selected>Select a product category</option>';
	$reqcat = $db->query('SELECT * FROM jktrade_cat WHERE cat_id>0 AND cat_parentcat=0');

		while ($datacat = $reqcat->fetch())
		{
		echo'<optgroup label="'.$datacat['cat_name'].'">';
				$reqsubcat = $db->query('SELECT * FROM jktrade_cat WHERE cat_parentcat='.$datacat['cat_id'].'');

				while ($subcat = $reqsubcat->fetch())
				{
					echo '<option value="'.$subcat['cat_id'].'">'.$subcat['cat_name'].'</option>';
				}
			echo'</optgroup>';
		}
	echo'</select>';
	
	return $data;
}

function isSeller ($db, $id, $user) // Check if the current user is the seller 
{
	$req = $db->query('SELECT pr_id FROM jktrade_products 
						WHERE pr_sellerID='.$user->id.' AND pr_id='.$id.'');
	$data = $req -> fetch();
	
	if(!$data){ // If the user doesn't own the product
	$own = 0;
	}
	else $own = 1;
	
	return $own;
}

// THE FOLLOWING FUNCTIONS ARE FROM PRODUCT.INC.PHP 

function count_product($db, $cat, $Allsubcat) // Send back the number of present products in the required cat (needed for pagination system)
{
	$nbProducts = 0; 
	
	if(!$Allsubcat) //Required cat has no sub-categories
	{
		$req = $db->query('SELECT COUNT(pr_id) as nbProducts FROM jktrade_products
						WHERE pr_cat = '.$cat.'');
		$data = $req->fetch();
		$nbProducts = $data[0];
						
	}
	else //There were at least one sub-cat in the required category
	{
		foreach($Allsubcat as $subcat){
			$req = $db->query('SELECT COUNT(pr_id) as nbProducts FROM jktrade_products
								WHERE pr_cat = '.$subcat.'');
			$data = $req -> fetch();
			$nbProducts += $data[0];
		}
	}
	
	return $nbProducts;
}

function count_categories($db){
		
	$sousCat = array();	
	$req = $db->query('SELECT COUNT(cat_id) as nbCategory FROM jktrade_cat');
	$data = $req->fetch();
	
	return $data['nbCategory'];
}


function search_sub_cat($db, $cat) // Send back an array containing all the sub-cat of the requested cat
{
	$data2 = array();
	$req = $db->query("SELECT cat_id FROM jktrade_cat WHERE cat_parentcat = $cat");
	$data = $req -> fetchAll(PDO::FETCH_COLUMN, 0);
	
	foreach($data as $subcat) // Second loop to search for the 3rd level of category
	{
		if($subcat) 
		{
			$req = $db->query("SELECT cat_id FROM jktrade_cat WHERE cat_parentcat = $subcat");
			$sousCat = $req -> fetchAll(PDO::FETCH_COLUMN, 0);
			foreach($sousCat as $thirdCat)
			{
				array_push($data2, $thirdCat);
			}
		}
	}
	
	if($cat) // Si la catégorie n'est pas All on rajoute la valeur de la catégorie mère dans le tableau
	{
		array_push($data, $cat);
	}
	
	foreach($data2 as $thirdCat)
	{
		array_push($data, $thirdCat);
	}
	
	return $data;
}

function check_category($db, $cat)
{
	$reqpr = $db->prepare('SELECT cat_id FROM jktrade_cat WHERE cat_id = :cat');
	$reqpr->execute(array(':cat' => $cat));
	$data = $reqpr->fetch();
	
	if($data){ 	// Required cat exists  
		$cat = $data[0];
	}
	else{ 	// Required cat doesn't exists so we redirect the user to All the products
		$cat = 0;
	}
	
	return $cat;
}


// Parsebb bbcode function. It's not ours.
// Courtesy of "Dan" from https://www.namepros.com/threads/php-simple-bbcode-parse-function.266965/
function parsebb($body) {
    $find = array(
        "@\n@",
        "@[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]@is", 
        "/\[url\=(.+?)\](.+?)\[\/url\]/is",
        "/\[b\](.+?)\[\/b\]/is", 
        "/\[i\](.+?)\[\/i\]/is", 
        "/\[u\](.+?)\[\/u\]/is", 
        "/\[color\=(.+?)\](.+?)\[\/color\]/is",
        "/\[size\=(.+?)\](.+?)\[\/size\]/is", 
        "/\[font\=(.+?)\](.+?)\[\/font\]/is",
        "/\[center\](.+?)\[\/center\]/is",
        "/\[right\](.+?)\[\/right\]/is",
        "/\[left\](.+?)\[\/left\]/is",
        "/\[img\](.+?)\[\/img\]/is",
        "/\[email\](.+?)\[\/email\]/is"
    );
    $replace = array(
        "<br />",
        "<a href=\"\\0\">\\0</a>",
        "<a href=\"$1\" target=\"_blank\">$2</a>",
        "<strong>$1</strong>",
        "<em>$1</em>",
        "<span style=\"text-decoration:underline;\">$1</span>",
        "<font color=\"$1\">$2</font>",
        "<font size=\"$1\">$2</font>",
        "<span style=\"font-family: $1\">$2</span>",
        "<div style=\"text-align:center;\">$1</div>",
        "<div style=\"text-align:right;\">$1</div>",
        "<div style=\"text-align:left;\">$1</div>",
        "<img src=\"$1\" alt=\"Image\" />",
        "<a href=\"mailto:$1\" target=\"_blank\">$1</a>"
    );
    $body = htmlspecialchars($body);
    $body = preg_replace($find, $replace, $body);
    return $body;
}